﻿using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class MapInstance : MonoBehaviour 
{
	public string name;
	public Texture2D texture;
	public pixelManager[] manager;

	public void CreateTexture()
	{
		GameObject obj = new GameObject();
		obj.name = name;

		int Columns = texture.width;
		int Rows = texture.height;

		for (int x = 0; x < Columns; x++) 
		{
			for (int y = 0; y < Rows; y++) 
			{
				Color color = texture.GetPixel(x,y);

				if(color != Color.white)
				{
					pixelManager current = getByColor(color);

					Transform t = Instantiate(current.block,new Vector3(x*0.8f,y*0.5f,0),current.block.rotation) as Transform;

					t.name = current.name;

					if(current.addLayerParams)
					{
						t.GetComponent<SpriteRenderer>().sortingOrder = Rows-y;
					}
					if(current.randomBlock)
					{
						int value = Random.Range(0,current.randomBlocks.Length);
						t.GetComponent<SpriteRenderer>().sprite = current.randomBlocks[value];
					}

					t.parent = obj.transform;
				}
			}
		}
	}

	public pixelManager getByColor(Color color)
	{
		foreach (pixelManager px in manager) 
		{
			if(px.pixelColor == color)
				return px;
		}

		Debug.Log("No Found This Color: "+color);
		return null;
	}

	[System.Serializable]
	public class pixelManager
	{
		public string name;
		public Transform block;
		public Color pixelColor;
		public bool randomBlock;
		public Sprite[] randomBlocks;
		public bool addLayerParams;
		public bool isTorch;
	}
}
